package com.jakewharton.rxbinding2.component;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.ohos.MainThreadDisposable;
import ohos.agp.components.Component;

import static com.jakewharton.rxbinding2.internal.Preconditions.checkMainThread;

final class ComponentScrollChangeEventObservable extends Observable<ComponentScrollChangeEvent> {
  private final Component view;

  ComponentScrollChangeEventObservable(Component view) {
    this.view = view;
  }

  @Override protected void subscribeActual(Observer<? super ComponentScrollChangeEvent> observer) {
    if (!checkMainThread(observer)) {
      return;
    }
    Listener listener = new Listener(view, observer);
    observer.onSubscribe(listener);
    view.setScrolledListener(listener);
  }

  static final class Listener extends MainThreadDisposable implements Component.ScrolledListener {
    private final Component view;
    private final Observer<? super ComponentScrollChangeEvent> observer;

    Listener(Component view, Observer<? super ComponentScrollChangeEvent> observer) {
      this.view = view;
      this.observer = observer;
    }

    @Override protected void onDispose() {
      view.setScrolledListener(null);
    }

    @Override
    public void onContentScrolled(Component component,  int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
      if (!isDisposed()) {
        observer.onNext(ComponentScrollChangeEvent.create(component, scrollX, scrollY, oldScrollX, oldScrollY));
      }
    }
  }
}
